// 读取HTML文件内容
const htmlContent = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>代理日志查看器</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f7fa;
            color: #2d3748;
            line-height: 1.6;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 30px;
            text-align: center;
        }

        .header h1 {
            color: #1a202c;
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            color: #718096;
            font-size: 1.1em;
        }

        .controls {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .refresh-btn {
            background: #4299e1;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s;
        }

        .refresh-btn:hover {
            background: #3182ce;
            transform: translateY(-2px);
        }

        .status {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .status-dot {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #48bb78;
        }

        .logs-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .logs-header {
            background: #edf2f7;
            padding: 20px;
            border-bottom: 1px solid #e2e8f0;
        }

        .logs-header h2 {
            color: #2d3748;
            margin-bottom: 5px;
        }

        .logs-count {
            color: #718096;
        }

        .log-item {
            border-bottom: 1px solid #e2e8f0;
            padding: 20px;
            transition: background 0.2s;
        }

        .log-item:hover {
            background: #f7fafc;
        }

        .log-item:last-child {
            border-bottom: none;
        }

        .log-meta {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 20px;
            margin-bottom: 15px;
        }

        .meta-item {
            display: flex;
            flex-direction: column;
        }

        .meta-label {
            font-size: 12px;
            color: #718096;
            text-transform: uppercase;
            font-weight: 600;
            margin-bottom: 5px;
        }

        .meta-value {
            font-size: 14px;
            color: #2d3748;
            font-weight: 500;
        }

        .method-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .method-get { background: #c6f6d5; color: #22543d; }
        .method-post { background: #bee3f8; color: #2a4365; }
        .method-put { background: #fbb6ce; color: #702459; }
        .method-delete { background: #fed7d7; color: #742a2a; }

        .json-container {
            background: #1a202c;
            border-radius: 8px;
            padding: 15px;
            overflow-x: auto;
        }

        .json-content {
            color: #e2e8f0;
            font-family: 'Monaco', 'Consolas', monospace;
            font-size: 13px;
            white-space: pre-wrap;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #718096;
        }

        .error {
            background: #fed7d7;
            color: #742a2a;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
        }

        @media (max-width: 768px) {
            .log-meta {
                grid-template-columns: 1fr;
                gap: 10px;
            }
            
            .controls {
                flex-direction: column;
                gap: 15px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 代理日志查看器</h1>
            <p>实时查看和监控代理请求日志</p>
        </div>

        <div class="controls">
            <div class="status">
                <div class="status-dot"></div>
                <span>在线监控</span>
            </div>
            <button class="refresh-btn" onclick="loadLogs()">🔄 刷新数据</button>
        </div>

        <div class="logs-container">
            <div class="logs-header">
                <h2>最近请求日志</h2>
                <div class="logs-count" id="logsCount">加载中...</div>
            </div>
            <div id="logsContent">
                <div class="loading">⏳ 正在加载日志数据...</div>
            </div>
        </div>
    </div>

    <script>
        async function loadLogs() {
            try {
                const response = await fetch('/logs');
                const data = await response.json();
                
                if (data.success) {
                    displayLogs(data.data, data.count);
                } else {
                    showError('加载失败: ' + (data.error || '未知错误'));
                }
            } catch (error) {
                showError('网络请求失败: ' + error.message);
            }
        }

        // 处理 JSON 字符串中的换行符和HTML转义字符
        function formatJsonString(obj) {
            let jsonString = JSON.stringify(obj, null, 2);
            // 将 JSON 字符串中的转义序列转换为实际字符用于显示
            var newlineRegex = /\\\\n/g;
            var carriageReturnRegex = /\\\\r/g;
            var tabRegex = /\\\\t/g;
            
            // 先处理转义字符
            jsonString = jsonString.replace(newlineRegex, '\\n')
                                  .replace(carriageReturnRegex, '\\r')
                                  .replace(tabRegex, '\\t');
            
            // 然后转义HTML特殊字符，防止被浏览器解析
            return jsonString.replace(/&/g, '&amp;')      // 必须先转义&符号
                            .replace(/</g, '&lt;')       // 转义小于号
                            .replace(/>/g, '&gt;')       // 转义大于号
                            .replace(/"/g, '&quot;');   // 转义双引号
        }

        function displayLogs(logs, count) {
            const logsContent = document.getElementById('logsContent');
            const logsCount = document.getElementById('logsCount');
            
            logsCount.textContent = '共 ' + count + ' 条记录';
            
            if (logs.length === 0) {
                logsContent.innerHTML = '<div class="loading">📝 暂无日志数据</div>';
                return;
            }

            logsContent.innerHTML = logs.map(log => {
                const methodClass = \`method-\${log.method.toLowerCase()}\`;
                const formattedDate = new Date(log.created_at).toLocaleString('zh-CN');
                const jsonString = formatJsonString(log.request_body);
                
                return \`
                    <div class="log-item">
                        <div class="log-meta">
                            <div class="meta-item">
                                <div class="meta-label">请求方法</div>
                                <div class="meta-value">
                                    <span class="method-badge \${methodClass}">\${log.method}</span>
                                </div>
                            </div>
                            <div class="meta-item">
                                <div class="meta-label">请求时间</div>
                                <div class="meta-value">\${formattedDate}</div>
                            </div>
                            <div class="meta-item">
                                <div class="meta-label">ID</div>
                                <div class="meta-value">#\${log.id}</div>
                            </div>
                        </div>
                        <div class="meta-item" style="margin-bottom: 15px;">
                            <div class="meta-label">请求URL</div>
                            <div class="meta-value" style="word-break: break-all;">\${log.url}</div>
                        </div>
                        <div class="meta-item">
                            <div class="meta-label">请求体 (JSON)</div>
                            <div class="json-container">
                                <div class="json-content">\${jsonString}</div>
                            </div>
                        </div>
                    </div>
                \`;
            }).join('');
        }

        function showError(message) {
            const logsContent = document.getElementById('logsContent');
            logsContent.innerHTML = \`<div class="error">❌ \${message}</div>\`;
        }

        // 页面加载时自动加载数据
        window.addEventListener('load', loadLogs);
        
        // 每30秒自动刷新一次
        setInterval(loadLogs, 30000);
    </script>
</body>
</html>`;

export default {

    async saveLog(db, bodyJsonString, proxy_url, method){
        try {
            await db.prepare('INSERT INTO proxy_logs (request_body, url, method) VALUES (?, ?, ?)').bind(bodyJsonString, proxy_url, method).run();
            console.log('数据已成功存储到 D1 数据库');
        } catch (error) {
            console.error('存储到 D1 数据库时出错:', error);
        }
    },


    
    async xiaozhiKimiApi(request, env, ctx){
        const proxy_url = "http://api.xiaozhi.me/master/chat/completions"
        const reqHeaders = new Headers(request.headers);
        const clonedRequest = request.clone();
        let bodyJson = await clonedRequest.json();
        const bodyJsonString = JSON.stringify(bodyJson);

        await this.saveLog(env.DB, bodyJsonString, proxy_url, request.method);
        reqHeaders.set('Authorization', 'Bearer ' + "xiaozhi-34165980");
        const response = await fetch(proxy_url, {
            method: request.method,
            headers: reqHeaders,
            body: bodyJsonString, // 用修改后的body
        });
        response.headers['Access-Control-Allow-Origin'] = '*';
        return response;
        
    },

	async fetch(request, env, ctx) {
		const url = new URL(request.url);

		// 如果请求路径是根路径或 /dashboard，返回HTML页面
		if (url.pathname === '/' || url.pathname === '/dashboard') {
			return new Response(htmlContent, {
				headers: {
					'Content-Type': 'text/html; charset=utf-8',
					'Access-Control-Allow-Origin': '*',
				},
			});
		}

		// 如果请求路径是 /logs，返回最后5条日志数据
		if (url.pathname === '/logs') {
			const result = await env.DB.prepare('SELECT * FROM proxy_logs ORDER BY created_at DESC LIMIT 5').all();

			// 将 request_body 字符串解析为 JSON 对象
			const processedData = result.results.map((row) => {
				return {
					...row,
					request_body: JSON.parse(row.request_body),
				};
			});

			return new Response(
				JSON.stringify({
					success: true,
					data: processedData,
					count: processedData.length,
				}),
				{
					headers: {
						'Content-Type': 'application/json',
						'Access-Control-Allow-Origin': '*',
					},
				}
			);
		}

		// 原有的代理逻辑
		// const TELEGRAPH_URL = "https://api.gptsapi.net";
        // const TELEGRAPH_URL = 'https://api.moonshot.cn';
        const TELEGRAPH_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
		const proxy_url = url.href.replace(url.origin, TELEGRAPH_URL);
        console.log(proxy_url);
		// 创建新的 Headers 对象，复制原始请求头
		const reqHeaders = new Headers(request.headers);
        let bodyJson = await request.json();
        const bodyJsonString = JSON.stringify(bodyJson);


		const response = await fetch(proxy_url, {
			method: request.method,
			headers: reqHeaders,
			body: bodyJsonString,
		});

        await this.saveLog(env.DB, bodyJsonString, proxy_url, request.method);


		response.headers['Access-Control-Allow-Origin'] = '*';
		return response;
	},
};
